package libs

import (
	"bufio"
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"strconv"
	"strings"
)

type ConfigS struct {
	RemoteReceiver string   `json:"remote_receiver"`
	LocalPath      string   `json:"local_path"`
	RemotePath     string   `json:"remote_dir"`
	MaxLimitSize   string   `json:"max_limit_size"`
	SyncActions    []string `json:"sync_actions"`
	IgnoreList     []string `json:"ignore_list"`
	IgnorePatterns []string `json:"ignore_patterns"`
	ListenDelay    int      `json:"listen_delay"`
	Debug          bool     `json:"debug"`
	LicenseKey     string   `json:"license_key"`
}

var Config ConfigS

func CreateDefaultConfig() {
	defaultConfig := ConfigS{
		RemoteReceiver: "http://server.com/script_path/",
		LocalPath:      "./",
		RemotePath:     "",
		MaxLimitSize:   "10MB",
		SyncActions:    []string{"CREATE", "MODIFY", "REMOVE", "RENAME"},
		IgnoreList:     []string{".git", ".vscode", "node_modules"},
		IgnorePatterns: []string{".tmp", ".temp", "~$", ".tmp", ".log", "EditToServer.php"},
		ListenDelay:    1000,
		Debug:          false,
		LicenseKey:     "",
	}

	jsonData, err := json.MarshalIndent(defaultConfig, "", "  ")
	if err != nil {
		DebugPrint("创建默认配置失败: %v\n", err)
		return
	}

	err = os.WriteFile("EditToServer.json", jsonData, 0644)
	if err != nil {
		DebugPrint("写入默认配置文件失败: %v\n", err)
		return
	}

	DebugPrint("已创建默认配置文件 EditToServer.json\n")
}

func LoadConfig() {

	data, err := os.ReadFile("EditToServer.json")
	if err != nil {
		DebugPrint("读取配置文件失败: %v\n", err)
		return
	}

	err = json.Unmarshal(data, &Config)
	if err != nil {
		DebugPrint("解析析配置文件失败: %v\n", err)
		return
	}
}

func SelectRemoteDir() {
	if Config.RemotePath != "" {
		PrintAndFlush(fmt.Sprintf("当前远程目录: %s\n", Config.RemotePath))
		PrintAndFlush("是否使用此远程目录? (y/n,直接回车默认为y): ")
		var response string
		fmt.Scanln(&response)

		response = strings.ToLower(strings.TrimSpace(response))
		if response == "" || response == "y" {
			DebugPrint("将使用当前保存的远程目录\n")
			return
		}
	}

	PrintAndFlush("正在从服务器获取可用的远程目录...\n")
	availableDirs, err := getAvailableDirsFromServer()
	if err != nil {
		PrintAndFlush(fmt.Sprintf("获取远程目录失败: %v\n", err))
		return
	}

	if len(availableDirs) == 0 {
		PrintAndFlush("没有可用的远程目录\n")
		return
	}

	PrintAndFlush("可用的远程目录:\n")
	for i, dir := range availableDirs {
		PrintAndFlush(fmt.Sprintf("%d. %s\n", i+1, dir))
	}

	reader := bufio.NewReader(os.Stdin)
	for {
		PrintAndFlush("请选择一个远程目录 (输入数字)，或输入 0 退出: ")
		input, err := reader.ReadString('\n')
		if err != nil {
			PrintAndFlush(fmt.Sprintf("读取输入失败: %v\n", err))
			continue
		}
		input = strings.TrimSpace(input)
		choice, err := strconv.Atoi(input)
		if err != nil {
			PrintAndFlush(fmt.Sprintf("输入错误，请输入一个数字。\n"))
			continue
		}
		if choice == 0 {
			PrintAndFlush("已取消选择远程目录。\n")
			return
		}
		if choice > 0 && choice <= len(availableDirs) {
			Config.RemotePath = availableDirs[choice-1]
			break
		}
		PrintAndFlush("无效的选择，请重试。\n")
	}

	jsonData, err := json.MarshalIndent(Config, "", "  ")
	if err != nil {
		PrintAndFlush(fmt.Sprintf("更新配置失败: %v\n", err))
		return
	}

	err = os.WriteFile("EditToServer.json", jsonData, 0644)
	if err != nil {
		PrintAndFlush(fmt.Sprintf("写入更新后的配置文件失败: %v\n", err))
		return
	}

	PrintAndFlush(fmt.Sprintf("远程目录已更新为: %s\n", Config.RemotePath))
}

func SelectLocalDir() string {
	currentPath, err := os.Getwd()
	if err != nil {
		DebugPrint("无法获取当前工作目录: %v\n", err)
		return ""
	}

	for {
		PrintAndFlush(fmt.Sprintf("当前目录: %s\n 直接回车选择当前目录\n", currentPath))
		PrintAndFlush("0. 返回上级目录\n")

		entries, err := os.ReadDir(currentPath)
		if err != nil {
			DebugPrint("读取目录失败: %v\n", err)
			return ""
		}

		var dirs []string
		for _, entry := range entries {
			if entry.IsDir() {
				fullPath := filepath.Join(currentPath, entry.Name())
				dirs = append(dirs, fullPath)
				PrintAndFlush(fmt.Sprintf("%d. %s\n", len(dirs), fullPath))
			}
		}

		PrintAndFlush("请选择（输入数字或直接回车）: ")

		var choice string
		choice, _ = bufio.NewReader(os.Stdin).ReadString('\n')
		choice = strings.TrimSpace(choice)

		if choice == "" {
			return currentPath
		}

		index, err := strconv.Atoi(choice)
		if err != nil {
			PrintAndFlush("无效的输入，请输入数字或直接回车。")
			continue
		}

		switch {
		case index == 0:
			parentDir := filepath.Dir(currentPath)
			if parentDir == currentPath {
				PrintAndFlush("已经在根目录，无法再向上。")
			} else {
				currentPath = parentDir
			}
		case index > 0 && index <= len(dirs):
			currentPath = dirs[index-1]
		default:
			PrintAndFlush("无效的选择，请重试。")
		}
	}
}

func (c *ConfigS) SaveConfig() error {
	data, err := json.MarshalIndent(c, "", "  ")
	if err != nil {
		return err
	}
	return os.WriteFile("EditToServer.json", data, 0644)
}
